package servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;

import javax.jdo.PersistenceManager;

import dataTypes.userDevice;


public class C2DMRegisterWithGoogle implements Serializable{

	private static final String GOOGLELOGINADDRESS = "https://www.google.com/accounts/ClientLogin";
	private static final String APPLICATIONEMAIL = "couponnowmobile@gmail.com";

	private static String authToken;

	
	public static String register(){
		try {
			
			//if (appManager.getInstance().getAuthToken() != null)	return;
			
			StringBuilder dataToSend = new StringBuilder();
			dataToSend.append("Email=").append(URLEncoder.encode(APPLICATIONEMAIL, "UTF-8"));
			dataToSend.append("&Passwd=").append(URLEncoder.encode("givi1234", "UTF-8"));
			dataToSend.append("&service=").append(URLEncoder.encode("ac2dm", "UTF-8"));
			dataToSend.append("&acountType=").append(URLEncoder.encode("HOSTED_OR_GOOGLE", "UTF-8"));
			dataToSend.append("&source=").append(URLEncoder.encode("CoupoNow", "UTF-8"));

			byte[] dataToSendByte = dataToSend.toString().getBytes("UTF-8");
			URL url = new URL(GOOGLELOGINADDRESS);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			OutputStream out = conn.getOutputStream();
			out.write(dataToSendByte);
			out.close();

			InputStream inputStream;
			
			if (conn.getResponseCode() == 200 || conn.getResponseCode() == 201){
				//String responseMessage = conn.getResponseMessage();
				inputStream = conn.getInputStream();
				authToken = parseToken(toString(inputStream));
				PersistenceManager pm = PMF.get().getPersistenceManager();
				userDevice userDevice = new userDevice("OURACCOUNT", authToken, "OURACCOUNT");
				pm.makePersistent(userDevice);
				pm.close();
				return "if  " + conn.getResponseMessage() + conn.getResponseCode() + toString(inputStream)  + authToken;
			}
			else{
				//Error!
				inputStream = conn.getErrorStream();
				authToken = parseToken(toString(inputStream));
				return "else  " + conn.getResponseMessage() + conn.getResponseCode() + toString(inputStream) + authToken;
			}

		} catch (Exception e) {
			// TODO Autos-generated catch block
			e.printStackTrace();
		}
		return authToken + "outside";
	}

	public static String getAuthToken() {
		return authToken;
	}

	private static String toString(InputStream inputStream) throws IOException {
	    String string;
	    StringBuilder outputBuilder = new StringBuilder();
	    if (inputStream != null) {
	      BufferedReader reader =
	          new BufferedReader(new InputStreamReader(inputStream));
	      while (null != (string = reader.readLine())) {
	        outputBuilder.append(string).append('\n');
	      }
	    }
	    return outputBuilder.toString();
	  }
	
	private static String parseToken(String resp){	
		StringTokenizer st = new StringTokenizer(resp, "=\n ");
		String finalToken= null;
		while(st.hasMoreElements()){
			if (st.nextToken().equals("Auth")){
				if (st.hasMoreElements())
					finalToken = st.nextToken();
				break;
			}

		}
		return finalToken;
	}
}
